package gaml.java.serializer;

import java.lang.reflect.Field;

import gaml.error.GamlException;
import gaml.java.ClassSerializer;
import gaml.yaml.ScalarNode;
import gaml.yaml.YamlNode;
import gaml.yaml.ahchor.YamlAnchorCodeStore;
import gaml.yaml.ahchor.YamlAnchorObjectStore;


/**
 * serialize data from enumeration object;
 * restore enumeration object from yaml serialization
 * @author shnireck
 *
 */
public  class EnumSerializer <T> implements ClassSerializer <T> {
	final static String enumValueFormat = " %d, %s"; // if u change this - change restore method of this class!
	
	Class <T> clazz;
	
	public EnumSerializer (Class <T> clazz) { this.clazz = clazz; }

	@Override
	public YamlNode createNode (YamlNode parent) {return new ScalarNode (parent); }

	@Override
	public T createObject () throws GamlException { return null; }

	@Override
	public Class <T> getObjectClass () { return clazz; }

	@Override
	public boolean noAnchor () { return true; }

	@Override
	public YamlNode serialize (YamlNode node, T object, YamlAnchorObjectStore anchors) throws GamlException {
		try {
			Field ordinal = Enum.class.getDeclaredField ("ordinal");
			ordinal.setAccessible (true);

			Field name = Enum.class.getDeclaredField ("name");
			name.setAccessible (true);

			node.setValue (String.format (enumValueFormat, ordinal.getInt (object), name.get (object).toString ()));
		} catch (Exception e) { throw new GamlException (e + " for class " + clazz.getName ()); }

		return node;
	}
	
	@Override
	public T restore (YamlNode node, T object, YamlAnchorCodeStore anchors) throws GamlException {
		return clazz.getEnumConstants () [Integer.parseInt (node.getValue ().trim ().substring (0, node.getValue ().indexOf (',')))];
	}
}
